// pages/homeEchart/homeEchart.js
import { initChart } from "../../utils/chart";
import { formatData, handleTags } from "../../utils/formatData";
import {
  maleArr,
  femaleArr,
  peerValueArr,
  refractionPeerValueArr,
  expleData,
} from "../../utils/mean";
//第二步配置optino
var db = wx.cloud.database();
var userCollection = db.collection("usersDataList");
var recordCollection = db.collection("recordsData");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      option: {},
      lazyLoad: true,
    },
    flag: null,
    active: 1,
    tagMsg: "",
    myBirthDate: "2000-01-01",
    activeBtn: 1,
    hospitalBtn: 1,
    projectBtn: 1,
    searchShow: false,
    navBarTxt: "",
    isHaveData: false,
    isButtonsDisabled: false,
    projectTag: [
      "所有",
      "近三月",
      "近半年",
      "近一年",
      "近两年",
      "半年前",
      "一年前",
      "两年前",
    ],
    hospitalTag: [],
    twoChangeData: [],
    allData: [],
    savedFilterState: null,
    detailInfo: {
      date: "",
      leftEye: "",
      rightEye: "",
      hitomiLeft: "",
      hitomiRight: "",
      diffInfo: {
        ALleft: "",
        ALright: "",
        left: "",
        right: "",
        speedALleft: "",
        speedALright: "",
        speedLeft: "",
        speedRight: "",
        timeDiff: "",
      },
      tags: {
        green: [],
        red: [],
      },
    },
    showDetail: false,
    isExpanded: false,
    activeEye: "right",
    sexRadio: "",
    isShared: false,
  },

  // 获取图表配置
  getBarOption() {
    const data = this.data.twoChangeData;
    console.log(data);

    if (!data || data.length === 0) {
      return {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          color: ["#0000FF", "#FF00FF"],
          data: ["左眼", "右眼"],
          left: "center",
          top: "bottom",
          textStyle: {
            color: "#999",
            fontSize: 12,
          },
          itemWidth: 30,
          itemHeight: 20,
          itemGap: 20,
          icon: "roundRect",
        },
        grid: {
          top: "70rpx",
          left: "0%",
          right: "4%",
          bottom: "0%",
          height: "75%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: [],
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "#999",
          },
        },
        yAxis: {
          type: "value",
          show: false,
          splitLine: {
            show: false,
          },
        },
        series: [],
        graphic: [
          {
            type: "text",
            left: "center",
            top: "middle",
            style: {
              text: "暂无数据，请先录入检查数据",
              fontSize: 14,
              fill: "#999",
            },
          },
        ],
      };
    }
    console.log(data);

    // 获取所有日期作为x轴数据，并根据createTime去重
    const dateMap = new Map(); // 用于存储每个日期最新的记录

    data.forEach((item) => {
      const date = new Date(item.selfMag.createDate.replace(/-/g, "/"));
      const dateKey = date.toISOString().split("T")[0]; // 使用日期作为key

      // 如果这个日期还没有记录，或者当前记录的createTime更新，则更新记录
      if (
        !dateMap.has(dateKey) ||
        (item.createTime && dateMap.get(dateKey).createTime < item.createTime)
      ) {
        dateMap.set(dateKey, {
          date: date,
          createTime: item.createTime || 0,
          data: JSON.parse(JSON.stringify(item)), // 创建深拷贝
        });
      }
    });

    // 将Map转换为数组并排序
    const uniqueData = Array.from(dateMap.values())
      .sort((a, b) => a.date - b.date)
      .map((item) => item.data);

    console.log("去重后的数据:", uniqueData);

    // 使用去重后的数据获取日期
    const dates = uniqueData.map((item) => {
      const date = new Date(item.selfMag.createDate.replace(/-/g, "/"));
      return date;
    });

    // 计算时间跨度
    const firstDate = dates[0];
    const lastDate = dates[dates.length - 1];
    const yearDiff = lastDate.getFullYear() - firstDate.getFullYear();
    const monthDiff =
      (lastDate.getFullYear() - firstDate.getFullYear()) * 12 +
      (lastDate.getMonth() - firstDate.getMonth());

    console.log("时间跨度:", {
      firstDate: firstDate.toLocaleDateString(),
      lastDate: lastDate.toLocaleDateString(),
      yearDiff,
      monthDiff,
    });

    // 根据时间跨度格式化日期
    const formattedDates = dates.map((date, index) => {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;

      // 如果是每年的第一个月，或者与上一条记录的年份不同，显示年份
      const prevDate = index > 0 ? dates[index - 1] : null;
      const isNewYear = !prevDate || prevDate.getFullYear() !== year;

      if (isNewYear) {
        return `${year}`;
      }

      // 其他情况显示月份
      return `${month}月`;
    });

    console.log(
      "原始日期:",
      dates.map((d) => d.toLocaleDateString())
    );
    console.log("格式化后的日期:", formattedDates);

    // 根据activeBtn选择不同的数据
    let leftEyeData, rightEyeData;
    if (this.data.activeBtn == 2) {
      // 屈光曲线
      leftEyeData = uniqueData.map((item) => item.ygd.hitomileft);
      rightEyeData = uniqueData.map((item) => item.ygd.hitomiright);
    } else if (this.data.activeBtn == 3) {
      // 眼轴vs屈光对比图
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "line",
            label: {
              show: true,
            },
          },
          formatter: (params) => {
            const currentData = uniqueData[params[0].dataIndex];
            const date = new Date(
              currentData.selfMag.createDate.replace(/-/g, "/")
            );
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();

            this.setData({
              detailInfo: {
                date: `${year}年${month}月${day}日`,
                leftEye: currentData.yzd.ALleft,
                rightEye: currentData.yzd.ALright,
                hitomiLeft: currentData.ygd.hitomileft,
                hitomiRight: currentData.ygd.hitomiright,
                diffInfo: currentData.hitomiDiff,
                hospital: currentData.selfMag.hospital,
                notes: currentData.tagSelect.message,
                tags: {
                  green: currentData.tipsGreen || [],
                  red: currentData.tipsRed || [],
                },
              },
              showDetail: true,
            });
            return "";
          },
        },
        legend: {
          color: ["#0000FF", "#FF00FF"],
          data: [
            this.data.activeEye === "right" ? "右眼眼轴" : "左眼眼轴",
            this.data.activeEye === "right" ? "右眼屈光" : "左眼屈光",
          ],
          left: "center",
          top: "bottom",
          textStyle: {
            color: "#999",
            fontSize: 12,
          },
          itemWidth: 30,
          itemHeight: 20,
          itemGap: 20,
          icon: "roundRect",
        },
        grid: {
          top: "70rpx",
          left: "0%",
          right: "4%",
          bottom: "0%",
          height: "75%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: formattedDates,
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: {
            color: "#999",
            interval: 0,
            rotate: 45,
            formatter: function (value) {
              if (!value.includes("月") && !value.includes("日")) {
                return `{bold|${value}}`;
              }
              return value;
            },
            rich: {
              bold: {
                fontWeight: "bold",
              },
            },
          },
        },
        yAxis: [
          {
            type: "value",
            name: "眼轴长度(mm)",
            nameTextStyle: {
              color: "#999",
            },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
            show: false,
          },
          {
            type: "value",
            name: "屈光度(D)",
            nameTextStyle: {
              color: "#999",
            },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
            show: false,
          },
        ],
        series: [
          {
            name: this.data.activeEye === "right" ? "右眼眼轴" : "左眼眼轴",
            type: "line",
            yAxisIndex: 0,
            data: uniqueData.map((item) =>
              this.data.activeEye === "right"
                ? item.yzd.ALright
                : item.yzd.ALleft
            ),
            color: "#FF00FF",
            lineStyle: {
              width: 3,
              color: "#FF00FF",
              shadowColor: "rgba(255,0,255, 0.5)",
              shadowBlur: 10,
              shadowOffsetY: 7,
            },
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  color: "#FF00FF",
                  fontWeight: "bold",
                  fontSize: 10,
                },
              },
            },
            smooth: true,
            connectNulls: true,
            symbol: "circle",
            symbolSize: 8,
            showSymbol: true,
          },
          {
            name: this.data.activeEye === "right" ? "右眼屈光" : "左眼屈光",
            type: "line",
            yAxisIndex: 1,
            data: uniqueData.map((item) =>
              this.data.activeEye === "right"
                ? item.ygd.hitomiright
                : item.ygd.hitomileft
            ),
            color: "#0000FF",
            lineStyle: {
              width: 3,
              color: "#0000FF",
              shadowColor: "rgba(0,0,255, 0.5)",
              shadowBlur: 10,
              shadowOffsetY: 7,
            },
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  color: "#0000FF",
                  fontWeight: "bold",
                  fontSize: 10,
                },
              },
            },
            smooth: true,
            connectNulls: true,
            symbol: "circle",
            symbolSize: 8,
            showSymbol: true,
          },
        ],
      };
      return option;
    } else if (this.data.activeBtn == 4) {
      // 眼轴速度图
      const data = this.data.twoChangeData;
      if (!data || data.length === 0) {
        return {
          tooltip: {
            trigger: "axis",
          },
          legend: {
            color: ["#0000FF", "#FF00FF"],
            data: ["左眼", "右眼"],
            left: "center",
            top: "bottom",
            textStyle: {
              color: "#999",
              fontSize: 12,
            },
            itemWidth: 30,
            itemHeight: 20,
            itemGap: 20,
            icon: "roundRect",
          },
          grid: {
            top: "70rpx",
            left: "0%",
            right: "15%",
            bottom: "0%",
            height: "75%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            data: [],
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: "#999",
            },
          },
          yAxis: {
            type: "value",
            show: false,
            splitLine: {
              show: false,
            },
          },
          series: [],
          graphic: [
            {
              type: "text",
              left: "center",
              top: "middle",
              style: {
                text: "暂无数据，请先录入检查数据",
                fontSize: 14,
                fill: "#999",
              },
            },
          ],
        };
      }

      // 获取所有日期作为x轴数据，并根据createTime去重
      const dateMap = new Map();
      data.forEach((item) => {
        const date = new Date(item.selfMag.createDate.replace(/-/g, "/"));
        const dateKey = date.toISOString().split("T")[0];
        if (
          !dateMap.has(dateKey) ||
          (item.createTime && dateMap.get(dateKey).createTime < item.createTime)
        ) {
          dateMap.set(dateKey, {
            date: date,
            createTime: item.createTime || 0,
            data: item,
          });
        }
      });

      const uniqueData = Array.from(dateMap.values())
        .sort((a, b) => a.date - b.date)
        .map((item) => item.data);

      const dates = uniqueData.map((item) => {
        const date = new Date(item.selfMag.createDate.replace(/-/g, "/"));
        return date;
      });

      const formattedDates = dates.map((date, index) => {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const prevDate = index > 0 ? dates[index - 1] : null;
        const isNewYear = !prevDate || prevDate.getFullYear() !== year;
        if (isNewYear) {
          return `${year}`;
        }
        return `${month}月`;
      });

      // 计算眼轴速度数据
      const speedData = uniqueData.map((item) => {
        // 根据年龄获取同龄值
        const age = item.selfMag.age;
        let peerValue = 0;

        console.log("计算同龄值:", {
          age: age,
          peerValueArr: peerValueArr,
        });

        // 根据年龄范围查找对应的同龄值
        const peerData = peerValueArr.find(
          (p) => age >= p.minAge && age <= p.maxAge
        );
        console.log("同龄值查找结果:", peerData);
        peerValue = peerData ? peerData.value : 0;

        console.log("最终同龄值:", peerValue);

        return {
          left: parseFloat(item.hitomiDiff.speedALleft),
          right: parseFloat(item.hitomiDiff.speedALright),
          peer: peerValue,
        };
      });

      const labelRight = {
        normal: {
          position: "right",
          color: "#999",
          fontSize: 10,
        },
      };

      const labelLeft = {
        normal: {
          position: "left",
          color: "#999",
          fontSize: 10,
        },
      };

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: (params) => {
            const currentData = uniqueData[params[0].dataIndex];
            const date = new Date(
              currentData.selfMag.createDate.replace(/-/g, "/")
            );
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();

            this.setData({
              detailInfo: {
                date: `${year}年${month}月${day}日`,
                leftEye: currentData.yzd.ALleft,
                rightEye: currentData.yzd.ALright,
                hitomiLeft: currentData.ygd.hitomileft,
                hitomiRight: currentData.ygd.hitomiright,
                diffInfo: currentData.hitomiDiff,
                hospital: currentData.selfMag.hospital,
                notes: currentData.tagSelect.message,
                tags: {
                  green: currentData.tipsGreen || [],
                  red: currentData.tipsRed || [],
                },
              },
              showDetail: true,
            });
            return "";
          },
        },
        legend: {
          color: ["#0000FF", "#FF00FF", "#00FF00"],
          data: ["左眼", "右眼", "同龄值"],
          left: "center",
          top: "bottom",
          textStyle: {
            color: "#999",
            fontSize: 12,
          },
          itemWidth: 30,
          itemHeight: 20,
          itemGap: 20,
          icon: "roundRect",
        },
        grid: {
          top: "70rpx",
          left: "0%",
          right: "15%",
          bottom: "0%",
          height: "75%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          position: "bottom",
          splitLine: {
            show: false,
          },
          axisLabel: {
            color: "#999",
            formatter: function (value) {
              return Math.round(value);
            },
          },
        },
        yAxis: {
          type: "category",
          data: formattedDates,
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: {
            color: "#999",
            interval: 0,
            rotate: 45,
            formatter: function (value) {
              if (!value.includes("月") && !value.includes("日")) {
                return `{bold|${value}}`;
              }
              return value;
            },
            rich: {
              bold: {
                fontWeight: "bold",
              },
            },
          },
        },
        series: [
          {
            name: "右眼",
            type: "bar",
            data: speedData.map((item) => ({
              value: item.right,
              label: {
                show: true,
                position: item.right >= 0 ? "right" : "left",
                formatter: "{c}",
                color: "#0000FF",
                fontSize: 10,
                distance: 5,
              },
            })),
            itemStyle: {
              color: "#0000FF",
              barBorderRadius: [0, 0, 0, 0],
            },
            barMaxWidth: 20,
            markLine: {
              silent: true,
              symbol: "none",
              lineStyle: {
                color: "#e58055",
                type: "dashed",
              },
              data: [
                {
                  xAxis: 0.2,
                  label: {
                    position: "end",
                    formatter: "警示线{c}",
                    rotate: 0,
                    color: "red",
                  },
                },
              ],
            },
          },
          {
            name: "左眼",
            type: "bar",
            data: speedData.map((item) => ({
              value: item.left,
              label: {
                show: true,
                position: item.left >= 0 ? "right" : "left",
                formatter: "{c}",
                color: "#FF00FF",
                fontSize: 10,
                distance: 5,
              },
            })),
            itemStyle: {
              color: "#FF00FF",
              barBorderRadius: [0, 0, 0, 0],
            },
            barMaxWidth: 20,
          },
          {
            name: "同龄值",
            type: "bar",
            data: speedData.map((item) => ({
              value: item.peer,
              label: {
                show: true,
                position: "right",
                formatter: "{c}",
                color: "#00FF00",
                fontSize: 10,
                distance: 5,
              },
            })),
            itemStyle: {
              color: "#00FF00",
              barBorderRadius: [0, 0, 0, 0],
            },
            barMaxWidth: 20,
          },
        ],
      };
      return option;
    } else if (this.data.activeBtn == 5) {
      // 屈光速度图
      const data = this.data.twoChangeData;
      if (!data || data.length === 0) {
        return {
          tooltip: {
            trigger: "axis",
          },
          legend: {
            color: ["#0000FF", "#FF00FF", "#00FF00"],
            data: ["左眼", "右眼", "同龄值"],
            left: "center",
            top: "bottom",
            textStyle: {
              color: "#999",
              fontSize: 12,
            },
            itemWidth: 30,
            itemHeight: 20,
            itemGap: 20,
            icon: "roundRect",
          },
          grid: {
            top: "70rpx",
            left: "0%",
            right: "15%",
            bottom: "0%",
            height: "75%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
            position: "bottom",
            splitLine: {
              show: false,
            },
            axisLabel: {
              color: "#999",
              formatter: function (value) {
                return Math.round(value);
              },
            },
          },
          yAxis: {
            type: "category",
            data: [],
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: {
              color: "#999",
            },
          },
          series: [],
          graphic: [
            {
              type: "text",
              left: "center",
              top: "middle",
              style: {
                text: "暂无数据，请先录入检查数据",
                fontSize: 14,
                fill: "#999",
              },
            },
          ],
        };
      }

      // 获取所有日期作为x轴数据，并根据createTime去重
      const dateMap = new Map();
      data.forEach((item) => {
        const date = new Date(item.selfMag.createDate.replace(/-/g, "/"));
        const dateKey = date.toISOString().split("T")[0];
        if (
          !dateMap.has(dateKey) ||
          (item.createTime && dateMap.get(dateKey).createTime < item.createTime)
        ) {
          dateMap.set(dateKey, {
            date: date,
            createTime: item.createTime || 0,
            data: item,
          });
        }
      });

      const uniqueData = Array.from(dateMap.values())
        .sort((a, b) => a.date - b.date)
        .map((item) => item.data);

      const dates = uniqueData.map((item) => {
        const date = new Date(item.selfMag.createDate.replace(/-/g, "/"));
        return date;
      });

      const formattedDates = dates.map((date, index) => {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const prevDate = index > 0 ? dates[index - 1] : null;
        const isNewYear = !prevDate || prevDate.getFullYear() !== year;
        if (isNewYear) {
          return `${year}`;
        }
        return `${month}月`;
      });

      // 计算屈光速度数据（独立使用refractionPeerValueArr）
      const speedData = uniqueData.map((item) => {
        const age = item.selfMag.age;
        let peerValue = 0;
        const peerData = refractionPeerValueArr.find(
          (p) => age >= p.minAge && age <= p.maxAge
        );
        peerValue = peerData ? peerData.value : 0;
        return {
          left: parseFloat(item.hitomiDiff.speedLeft),
          right: parseFloat(item.hitomiDiff.speedRight),
          peer: peerValue,
        };
      });

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: (params) => {
            const currentData = uniqueData[params[0].dataIndex];
            const date = new Date(
              currentData.selfMag.createDate.replace(/-/g, "/")
            );
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();

            this.setData({
              detailInfo: {
                date: `${year}年${month}月${day}日`,
                leftEye: currentData.yzd.ALleft,
                rightEye: currentData.yzd.ALright,
                hitomiLeft: currentData.ygd.hitomileft,
                hitomiRight: currentData.ygd.hitomiright,
                diffInfo: currentData.hitomiDiff,
                hospital: currentData.selfMag.hospital,
                notes: currentData.tagSelect.message,
                tags: {
                  green: currentData.tipsGreen || [],
                  red: currentData.tipsRed || [],
                },
              },
              showDetail: true,
            });
            return "";
          },
        },
        legend: {
          color: ["#0000FF", "#FF00FF", "#00FF00"],
          data: ["左眼", "右眼", "同龄值"],
          left: "center",
          top: "bottom",
          textStyle: {
            color: "#999",
            fontSize: 12,
          },
          itemWidth: 30,
          itemHeight: 20,
          itemGap: 20,
          icon: "roundRect",
        },
        grid: {
          top: "70rpx",
          left: "0%",
          right: "15%",
          bottom: "0%",
          height: "75%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          position: "bottom",
          splitLine: {
            show: false,
          },
          axisLabel: {
            color: "#999",
            formatter: function (value) {
              return Math.round(value);
            },
          },
        },
        yAxis: {
          type: "category",
          data: formattedDates,
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: {
            color: "#999",
            interval: 0,
            rotate: 45,
            formatter: function (value) {
              if (!value.includes("月") && !value.includes("日")) {
                return `{bold|${value}}`;
              }
              return value;
            },
            rich: {
              bold: {
                fontWeight: "bold",
              },
            },
          },
        },
        series: [
          {
            name: "右眼",
            type: "bar",
            data: speedData.map((item) => ({
              value: item.right,
              label: {
                show: true,
                position: item.right >= 0 ? "right" : "left",
                formatter: "{c}",
                color: "#0000FF",
                fontSize: 10,
                distance: 5,
              },
            })),
            itemStyle: {
              color: "#0000FF",
              barBorderRadius: [0, 0, 0, 0],
            },
            barMaxWidth: 20,
            markLine: {
              silent: true,
              symbol: "none",
              lineStyle: {
                color: "#e58055",
                type: "dashed",
              },
              data: [
                {
                  xAxis: 50,
                  label: {
                    position: "end",
                    formatter: "警示线{c}",
                    rotate: 0,
                    color: "red",
                  },
                },
              ],
            },
          },
          {
            name: "左眼",
            type: "bar",
            data: speedData.map((item) => ({
              value: item.left,
              label: {
                show: true,
                position: item.left >= 0 ? "right" : "left",
                formatter: "{c}",
                color: "#FF00FF",
                fontSize: 10,
                distance: 5,
              },
            })),
            itemStyle: {
              color: "#FF00FF",
              barBorderRadius: [0, 0, 0, 0],
            },
            barMaxWidth: 20,
          },
          {
            name: "同龄值",
            type: "bar",
            data: speedData.map((item) => ({
              value: item.peer,
              label: {
                show: true,
                position: "right",
                formatter: "{c}",
                color: "#00FF00",
                fontSize: 10,
                distance: 5,
              },
            })),
            itemStyle: {
              color: "#00FF00",
              barBorderRadius: [0, 0, 0, 0],
            },
            barMaxWidth: 20,
          },
        ],
      };
      return option;
    } else {
      // 眼轴曲线
      leftEyeData = uniqueData.map((item) => item.yzd.ALleft);
      rightEyeData = uniqueData.map((item) => item.yzd.ALright);
    }

    // 计算数据点之间的时间间隔
    const timeIntervals = [];
    for (let i = 1; i < dates.length; i++) {
      const interval = dates[i] - dates[i - 1];
      timeIntervals.push(interval);
    }

    // 计算平均时间间隔
    const avgInterval =
      timeIntervals.reduce((a, b) => a + b, 0) / timeIntervals.length;
    console.log("平均时间间隔(天):", avgInterval / (1000 * 60 * 60 * 24));

    // 根据时间间隔调整x轴配置
    const xAxisConfig = {
      type: "category",
      data: formattedDates,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#999",
        interval: 0, // 强制显示所有标签
        rotate: 45, // 旋转标签以防重叠
        formatter: function (value) {
          // 如果是年份，加粗显示
          if (!value.includes("月") && !value.includes("日")) {
            return `{bold|${value}}`;
          }
          return value;
        },
        rich: {
          bold: {
            fontWeight: "bold",
          },
        },
      },
      axisPointer: {
        type: "line",
        label: {
          show: true,
        },
      },
    };

    // 根据时间间隔调整grid配置
    const gridConfig = {
      top: "70rpx",
      left: "0%",
      right: "0%", // 修改为0%，使图表占满宽度
      bottom: "0%",
      height: "75%",
      containLabel: true,
    };

    let yAxisConfig;
    if (this.data.activeBtn == 1) {
      const allValues = [...leftEyeData, ...rightEyeData];
      const numericValues = allValues
        .map((v) => parseFloat(v))
        .filter((v) => !isNaN(v));

      let minValue = "dataMin";
      if (numericValues.length > 0) {
        minValue = Math.floor(Math.min(...numericValues));
      }

      yAxisConfig = {
        type: "value",
        min: minValue,
        interval: 0.5,
        splitLine: {
          show: false,
          lineStyle: {
            type: "dashed",
            color: "#ccc",
          },
        },
        axisLabel: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
      };
    } else {
      yAxisConfig = {
        type: "value",
        show: false,
        splitLine: {
          show: false,
        },
      };
    }

    const option = {
      tooltip: {
        trigger: "axis",
        formatter: (params) => {
          const currentData = uniqueData[params[0].dataIndex];
          const date = new Date(
            currentData.selfMag.createDate.replace(/-/g, "/")
          );
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();

          this.setData({
            detailInfo: {
              date: `${year}年${month}月${day}日`,
              leftEye: currentData.yzd.ALleft,
              rightEye: currentData.yzd.ALright,
              hitomiLeft: currentData.ygd.hitomileft,
              hitomiRight: currentData.ygd.hitomiright,
              diffInfo: currentData.hitomiDiff,
              hospital: currentData.selfMag.hospital,
              notes: currentData.tagSelect.message,
              tags: {
                green: currentData.tipsGreen || [],
                red: currentData.tipsRed || [],
              },
            },
            showDetail: true,
          });
          return "";
        },
      },
      legend: {
        color: ["#0000FF", "#FF00FF"],
        data: ["左眼", "右眼"],
        left: "center",
        top: "bottom",
        textStyle: {
          color: "#999",
          fontSize: 12,
        },
        itemWidth: 30,
        itemHeight: 20,
        itemGap: 20,
        icon: "roundRect",
      },
      grid: gridConfig,
      xAxis: xAxisConfig,
      yAxis: yAxisConfig,
      series: [
        {
          name: "右眼",
          type: "line",
          data: rightEyeData,
          color: "#0000FF",
          lineStyle: {
            width: 3,
            color: "#0000FF",
            shadowColor: "rgba(0,0,255, 0.5)",
            shadowBlur: 10,
            shadowOffsetY: 7,
          },
          itemStyle: {
            normal: {
              label: {
                show: true,
                color: "#0000FF",
                fontWeight: "bold",
                fontSize: 10,
              },
            },
          },
          smooth: true,
          connectNulls: true,
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
          label: {
            show: true,
            position: "top",
            formatter: function (params) {
              return params.value;
            },
          },
        },
        {
          name: "左眼",
          type: "line",
          data: leftEyeData,
          color: "#FF00FF",
          lineStyle: {
            width: 3,
            color: "#FF00FF",
            shadowColor: "rgba(255,0,255, 0.5)",
            shadowBlur: 10,
            shadowOffsetY: 7,
          },
          itemStyle: {
            normal: {
              label: {
                show: true,
                color: "#FF00FF",
                fontWeight: "bold",
                fontSize: 10,
              },
            },
          },
          smooth: true,
          connectNulls: true,
          symbol: "circle",
          symbolSize: 8,
          showSymbol: true,
          label: {
            show: true,
            position: "top",
            formatter: function (params) {
              return params.value;
            },
          },
        },
      ],
    };

    console.log("图表配置:", option);
    return option;
  },
  toggleSearchShow() {
    this.setData({
      searchShow: !this.data.searchShow,
    });
  },
  onChange() {
    wx.switchTab({
      url: "/pages/home/home",
    });
  },
  changBtn(e) {
    let value = e.currentTarget.dataset.item;
    if (this.data.isButtonsDisabled && value == 6) {
      return;
    }

    // 如果是筛选按钮（第6项），保存当前筛选条件并打开过滤弹窗
    if (value == 6) {
      this.setData({
        savedFilterState: {
          hospitalBtn: this.data.hospitalBtn,
          projectBtn: this.data.projectBtn,
          tagMsg: this.data.tagMsg,
        },
        searchShow: true,
      });
      return;
    }

    // 其他按钮切换图表类型
    this.setData({
      activeBtn: value,
    });

    // 重新初始化图表
    this.ecComponent = this.selectComponent("#mychart");
    this.ecComponent.init((canvas, width, height) => {
      return initChart(canvas, width, height, this.getBarOption());
    });
  },
  changeTag(e) {
    // 保存当前的筛选条件作为上一次的状态
    this.setData({
      savedFilterState: {
        hospitalBtn: this.data.hospitalBtn,
        projectBtn: this.data.projectBtn,
        tagMsg: this.data.tagMsg,
      },
      hospitalBtn: e.currentTarget.dataset.item,
    });
  },
  changeproTag(e) {
    // 保存当前的筛选条件作为上一次的状态
    this.setData({
      savedFilterState: {
        hospitalBtn: this.data.hospitalBtn,
        projectBtn: this.data.projectBtn,
        tagMsg: this.data.tagMsg,
      },
      projectBtn: e.currentTarget.dataset.item,
    });
  },
  onConfirm() {
    // 使用完整数据进行过滤
    let filteredData = [...this.data.allData];
    let filterConditions = [];

    // 根据医院标签过滤
    if (this.data.hospitalBtn !== 1) {
      const selectedHospital = this.data.hospitalTag[this.data.hospitalBtn - 1];
      filterConditions.push(selectedHospital);
      filteredData = filteredData.filter(
        (item) => item.selfMag.hospital === selectedHospital
      );
    }

    // 根据时间标签过滤
    if (this.data.projectBtn !== 1) {
      const now = new Date();
      const selectedTimeRange = this.data.projectTag[this.data.projectBtn - 1];
      filterConditions.push(selectedTimeRange);

      filteredData = filteredData.filter((item) => {
        const itemDate = new Date(item.selfMag.createDate.replace(/-/g, "/"));
        const diffTime = now - itemDate;
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

        switch (selectedTimeRange) {
          case "近三月":
            return diffDays <= 90;
          case "近半年":
            return diffDays <= 180;
          case "近一年":
            return diffDays <= 365;
          case "近两年":
            return diffDays <= 730;
          case "半年前":
            return diffDays > 180;
          case "一年前":
            return diffDays > 365;
          case "两年前":
            return diffDays > 730;
          default:
            return true;
        }
      });
    }

    // 检查是否有匹配的数据
    if (filteredData.length === 0) {
      // 构建提示信息
      let message = "未找到";
      if (filterConditions.length > 0) {
        message += filterConditions.join("、") + "的";
      }
      message += "检查数据";

      wx.showToast({
        title: message,
        icon: "none",
        duration: 2000,
      });

      // 恢复到选择前的筛选条件
      const savedState = this.data.savedFilterState;
      this.setData(
        {
          hospitalBtn: savedState.hospitalBtn,
          projectBtn: savedState.projectBtn,
          tagMsg: savedState.tagMsg,
          searchShow: false,
        },
        () => {
          // 根据恢复的筛选条件重新过滤数据
          let restoredData = [...this.data.allData];

          // 根据医院标签过滤
          if (savedState.hospitalBtn !== 1) {
            const selectedHospital =
              this.data.hospitalTag[savedState.hospitalBtn - 1];
            restoredData = restoredData.filter(
              (item) => item.selfMag.hospital === selectedHospital
            );
          }

          // 根据时间标签过滤
          if (savedState.projectBtn !== 1) {
            const now = new Date();
            const selectedTimeRange =
              this.data.projectTag[savedState.projectBtn - 1];
            restoredData = restoredData.filter((item) => {
              const itemDate = new Date(
                item.selfMag.createDate.replace(/-/g, "/")
              );
              const diffTime = now - itemDate;
              const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

              switch (selectedTimeRange) {
                case "近三月":
                  return diffDays <= 90;
                case "近半年":
                  return diffDays <= 180;
                case "近一年":
                  return diffDays <= 365;
                case "近两年":
                  return diffDays <= 730;
                case "半年前":
                  return diffDays > 180;
                case "一年前":
                  return diffDays > 365;
                case "两年前":
                  return diffDays > 730;
                default:
                  return true;
              }
            });
          }

          // 更新数据并重新初始化图表
          this.setData(
            {
              twoChangeData: restoredData,
            },
            () => {
              this.ecComponent = this.selectComponent("#mychart");
              this.ecComponent.init((canvas, width, height) => {
                return initChart(canvas, width, height, this.getBarOption());
              });
            }
          );
        }
      );
      return;
    }

    // 更新过滤后的数据
    this.setData({
      twoChangeData: filteredData,
      searchShow: false,
    });

    // 更新图表
    this.ecComponent = this.selectComponent("#mychart");
    this.ecComponent.init((canvas, width, height) => {
      return initChart(canvas, width, height, this.getBarOption());
    });

    // 更新标签显示
    if (this.data.hospitalBtn == 1 && this.data.projectBtn == 1) {
      this.setData({
        tagMsg: "",
      });
    } else if (this.data.hospitalBtn == 1) {
      this.setData({
        tagMsg: this.data.projectTag[this.data.projectBtn - 1],
      });
    } else if (this.data.projectBtn == 1) {
      this.setData({
        tagMsg: this.data.hospitalTag[this.data.hospitalBtn - 1],
      });
    } else {
      this.setData({
        tagMsg:
          this.data.hospitalTag[this.data.hospitalBtn - 1] +
          " " +
          this.data.projectTag[this.data.projectBtn - 1],
      });
    }
  },
  onCancel() {
    this.setData({
      searchShow: false,
    });
  },
  // 跳转到首页
  goIndexPage() {
    wx.navigateTo({
      url: "/pages/index/index",
    });
  },
  updateNavBarText() {
    // 根据 flag 参数决定数据加载方式
    if (this.data.flag == 1) {
      const { sortedData, hospitalTag } = formatData(
        expleData,
        this.data.myBirthDate
      );
      // 先调用handleTags处理数据
      const processedData = handleTags(sortedData);
      // 将数据反转，使最早的日期在前
      const reversedData = [...processedData].reverse();
      reversedData.forEach((item) => {
        item.ygd.hitomileft = item.ygd.hitomileft * 100;
        item.ygd.hitomiright = item.ygd.hitomiright * 100;
      });

      this.setData({
        navBarTxt: `退轴了小程序`,
        twoChangeData: reversedData,
        allData: reversedData,
        hospitalTag: hospitalTag,
        isHaveData: true,
        isButtonsDisabled: false, // 有示例数据时启用按钮
      });
      return;
    }

    let newText = "退轴了小程序"; // 默认文本
    const openid = wx.getStorageSync("openid"); // 获取当前用户的 openid
    const sharedOpenid = wx.getStorageSync("sharedOpenid"); // 获取分享者的openid
    const sharedUserId = wx.getStorageSync("sharedUserId"); // 获取分享者的userId

    // 如果是分享进入，使用分享者的数据
    if (this.data.isShared && sharedOpenid && sharedUserId) {
      console.log("分享数据:", {
        isShared: this.data.isShared,
        sharedOpenid,
        sharedUserId,
      });

      recordCollection
        .where({
          _openid: sharedOpenid,
          _id: Number(sharedUserId),
        })
        .get({
          success: (res) => {
            if (res.data && res.data.length > 0) {
              const recordsData = res.data[0].recordsdata;
              const sharedUserdata = res.data[0].userdata;
              if (recordsData) {
                try {
                  const { sortedData, hospitalTag } = formatData(
                    recordsData,
                    sharedUserdata.birthDate
                  );
                  // 先调用handleTags处理数据
                  const processedData = handleTags(sortedData);
                  // 将数据反转，使最早的日期在前
                  const reversedData = [...processedData].reverse();
                  reversedData.forEach((item) => {
                    item.ygd.hitomileft = item.ygd.hitomileft * 100;
                    item.ygd.hitomiright = item.ygd.hitomiright * 100;
                  });

                  this.setData({
                    hospitalTag: hospitalTag,
                    allData: reversedData,
                    twoChangeData: reversedData,
                    isHaveData: true,
                    isButtonsDisabled: false,
                    navBarTxt: `${sharedUserdata.nickName} · 退轴了小程序`,
                    sexRadio: sharedUserdata.sexRadio,
                  });

                  this.ecComponent = this.selectComponent("#mychart");
                  this.ecComponent.init((canvas, width, height) => {
                    return initChart(
                      canvas,
                      width,
                      height,
                      this.getBarOption()
                    );
                  });
                } catch (error) {
                  console.error("处理分享数据时出错：", error);
                  this.setData({
                    isButtonsDisabled: true,
                  });
                }
              }
            }
          },
          fail: (err) => {
            wx.showToast({
              title: "获取分享数据失败",
              icon: "none",
            });
            this.setData({
              isButtonsDisabled: true,
            });
          },
        });
      return;
    } else {
      wx.setStorageSync("isShared", false);
      this.setData({
        isShared: false,
      });
    }

    // 原有的数据加载逻辑
    userCollection
      .where({
        _openid: openid,
      })
      .get({
        success: (res) => {
          if (res.data[0].records.length === 0) {
            this.setData({
              navBarTxt: newText,
              isHaveData: false,
              twoChangeData: [],
              goinsertText: "建档",
              isButtonsDisabled: true, // 没有数据时禁用按钮
            });
            return;
          }

          let nickName = "";
          let sexRadio = "";
          const selectedUserId = wx.getStorageSync("selectedUserId");

          // 如果建档后的用户没有检查单，则显示建档
          if (res.data[0].records && res.data[0].records.length > 0) {
            if (selectedUserId) {
              // 根据 selectedUserId 查找匹配的记录
              const matchedRecord = res.data[0].records.find(
                (record) => record.id === selectedUserId
              );
              if (matchedRecord) {
                nickName = matchedRecord.nickName;
                sexRadio = matchedRecord.sexRadio;
                // 更新数据
                this.setData({
                  userData: res.data,
                  isHaveData: true,
                  goinsertText: "录入检查单",
                  myBirthDate: matchedRecord.birthDate,
                  sexRadio: matchedRecord.sexRadio,
                  isButtonsDisabled: false, // 有数据时启用按钮
                });
              }
            } else {
              // 如果没有 selectedUserId，使用最后一条记录
              const lastIndex = res.data[0].records.length - 1;
              nickName = res.data[0].records[lastIndex].nickName;
              sexRadio = res.data[0].records[lastIndex].sexRadio;
              // 设置最后一条记录的birthDate
              this.setData({
                myBirthDate: res.data[0].records[lastIndex].birthDate,
                sexRadio: res.data[0].records[lastIndex].sexRadio,
                isHaveData: true,
                goinsertText: "录入检查单",
                isButtonsDisabled: false, // 有数据时启用按钮
              });
            }
          }

          if (nickName) {
            this.setData({
              navBarTxt: `${nickName} · 退轴了小程序`,
            });
          }

          // 确保上面的判断都完成后再执行下面的查询
          if (selectedUserId) {
            recordCollection
              .where({
                _openid: openid,
                _id: selectedUserId,
              })
              .get({
                success: (res) => {
                  console.log("获取数据成功：", res);
                  if (res.data && res.data.length > 0) {
                    const recordsData = res.data[0].recordsdata;
                    if (recordsData) {
                      try {
                        const { sortedData, hospitalTag } = formatData(
                          recordsData,
                          this.data.myBirthDate
                        );
                        console.log(sortedData, "homeechart");

                        // 先调用handleTags处理数据
                        const processedData = handleTags(sortedData);
                        // 将数据反转，使最早的日期在前
                        const reversedData = [...processedData].reverse();
                        reversedData.forEach((item) => {
                          item.ygd.hitomileft = item.ygd.hitomileft * 100;
                          item.ygd.hitomiright = item.ygd.hitomiright * 100;
                        });

                        // 保存完整数据
                        this.setData({
                          allData: reversedData,
                          twoChangeData: reversedData,
                          hospitalTag: hospitalTag,
                          isButtonsDisabled: false,
                          activeBtn: 1,
                        });

                        this.ecComponent = this.selectComponent("#mychart");
                        this.ecComponent.init((canvas, width, height) => {
                          return initChart(
                            canvas,
                            width,
                            height,
                            this.getBarOption()
                          );
                        });
                      } catch (error) {
                        this.setData({
                          isButtonsDisabled: true,
                        });
                      }
                    } else {
                      this.setData({
                        allData: [],
                        twoChangeData: [],
                        isButtonsDisabled: true,
                      });
                    }
                  } else {
                    this.setData({
                      allData: [],
                      twoChangeData: [],
                      isButtonsDisabled: true,
                    });
                  }
                },
                fail: (err) => {
                  console.error("获取数据失败：", err);
                  this.setData({
                    isButtonsDisabled: true, // 获取数据失败时禁用按钮
                  });
                  wx.showToast({
                    title: "获取数据失败",
                    icon: "none",
                  });
                },
                complete: () => {
                  wx.hideLoading();
                },
              });
          }
        },
        fail: (err) => {
          console.error("获取用户数据失败:", err);
          this.setData({
            navBarTxt: newText,
            isHaveData: false,
            isButtonsDisabled: true, // 获取用户数据失败时禁用按钮
          });
        },
      });
  },
  changeUserPage() {
    if (this.data.flag == 1 || this.data.isShared) {
      wx.navigateTo({
        url: "/pages/addPage/addPage",
      });
    } else {
      wx.navigateTo({
        url: "/pages/changeUser/changeUser",
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 初始化时设置按钮为禁用状态
    this.setData({
      isButtonsDisabled: true,
      isHaveData: false,
      twoChangeData: [],
    });

    // 检查是否是分享进入
    // if (
    //   options.shared === "true" &&
    //   options.openid &&
    //   options.userId &&
    //   options.birthDate
    // ) {
    //   // 保存分享者的openid、userId和birthDate
    //   wx.setStorageSync("sharedOpenid", options.openid);
    //   wx.setStorageSync("sharedUserId", options.userId);
    //   wx.setStorageSync("isShared", true);
    //   this.setData({
    //     isShared: true,
    //     myBirthDate: options.birthDate,
    //   });
    // } else {
    //   // 非分享进入时，确保isShared为false
    //   wx.setStorageSync("isShared", false);
    //   this.setData({
    //     isShared: false,
    //   });
    // }

    // 立即初始化图表显示暂无数据提示
    this.ecComponent = this.selectComponent("#mychart");
    this.ecComponent.init((canvas, width, height) => {
      return initChart(canvas, width, height, this.getBarOption());
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const flag = wx.getStorageSync("homeFlag");
    const isShared = wx.getStorageSync("isShared");

    if (flag) {
      this.setData({
        flag: flag,
        isButtonsDisabled: false, // 有示例数据时启用按钮
      });
    } else {
      // 没有示例数据时，先禁用按钮
      this.setData({
        isButtonsDisabled: true,
        isHaveData: false,
        twoChangeData: [],
      });
      // 确保显示暂无数据提示
      this.ecComponent = this.selectComponent("#mychart");
      this.ecComponent.init((canvas, width, height) => {
        return initChart(canvas, width, height, this.getBarOption());
      });
    }

    // 确保isShared状态正确
    this.setData({
      isShared: isShared || false,
    });

    this.updateNavBarText();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const openid = wx.getStorageSync("openid");
    const selectedUserId = wx.getStorageSync("selectedUserId");
    const nickName = this.data.navBarTxt.split("·")[0].trim();
    const myBirthDate = this.data.myBirthDate;

    return {
      title: `${nickName}的近视检查数据`,
      desc: "查看我的近视检查数据",
      path: `/pages/homeEchart/homeEchart?shared=true&openid=${openid}&userId=${selectedUserId}&birthDate=${myBirthDate}`,
      imageUrl: "../../images/share.png",
      success: function (res) {
        wx.showToast({
          title: "分享成功",
          icon: "success",
        });
      },
      fail: function (res) {
        wx.showToast({
          title: "分享失败",
          icon: "none",
        });
      },
    };
  },

  onChartMouseOut() {
    this.setData({
      showDetail: false,
      isExpanded: false,
    });
  },

  // 添加切换眼睛的方法
  switchEye(e) {
    const eye = e.currentTarget.dataset.eye;
    this.setData({
      activeEye: eye,
    });

    // 重新初始化图表
    this.ecComponent = this.selectComponent("#mychart");
    this.ecComponent.init((canvas, width, height) => {
      return initChart(canvas, width, height, this.getBarOption());
    });
  },

  toggleExpand() {
    this.setData({
      isExpanded: !this.data.isExpanded,
    });
  },

  closeDetail() {
    this.setData({
      showDetail: false,
      isExpanded: false,
    });
  },
});
